﻿var SCA = SCA || {};
SCA.UI = SCA.UI || {};
SCA.UI.Mappings = SCA.UI.Mappings || {};

SCA.UI.Mappings.Dialog = function (mappingsTable) {
    this.mappingsTable = mappingsTable;

    this.LocationSelectionDialog;

    var thisContext = this;

    var FOLDER_TYPE_WEB = "Sobiens.Connectors.Entities.SharePoint.SPWeb";
    var FOLDER_TYPE_LIST = " Sobiens.Connectors.Entities.SharePoint.SPList";
    var FOLDER_TYPE_FOLDER = "Sobiens.Connectors.Entities.SharePoint.SPFolder";

    this.SelectedFolderType = null;

    this.Setup = function () {
        jQuery("#NewMappingButton").button().click(function () {
            jQuery("#MappingEditDialog").dialog({ title: "New Mapping", width: "600px" });
        });

        GetDialog().on("dialogclose", function (event, ui) { jQuery(".validity-modal-msg").hide(); });
        jQuery("#ButtonMappingSelectLocation").click(function () { thisContext.OpenLocationTree() });
        
        GetRadioButtonLocationTypeGeneral().change(ShowHideLocationControls);
        GetRadioButtonLocationTypeSpecific().change(ShowHideLocationControls);
    }
    

    var ShowHideLocationControls = function () {
        
        if (GetSelectedRadioButtonLocationType().val() == "General") {
            jQuery("#MappingSiteSettingRow").hide();
            jQuery("#MappingLocationRow").hide();
            jQuery("#MappingContentTypeRow").hide();
            jQuery("#MappingServicePropertyByDropDownRow").hide();
            jQuery("#MappingServicePropertyByTextBoxRow").show();
        }
        else {
            jQuery("#MappingServicePropertyByTextBoxRow").hide();
            jQuery("#MappingSiteSettingRow").show();
            jQuery("#MappingLocationRow").show();
            jQuery("#MappingContentTypeRow").show();
            jQuery("#MappingServicePropertyByDropDownRow").show();
        }
    }
        


    this.New = function () {
        GetHiddenInputIndex().val("-1");
        
        GetFirstRadioButtonApplicationType().attr("checked", true);
        GetFirstRadioButtonLocationType().attr("checked", true);
        FillAllDropDownLists();
        GetSpanLocation().text("");
        GetDropDownContentType().empty();
        GetInputServiceProperty().val("");

        //TODO: for application property & service property dropdowns
        ShowHideLocationControls();

        this.SelectedFolderType = null;
    }

    this.Load = function (index) {
        try {
            if (SCA.AppConfiguration.FolderSettings == null)
                return;

            var mapping = GetMapping(index);

            FillAllDropDownLists();

            GetRadioButtonApplicationType(mapping).attr("checked", true);
            if (mapping.BasicFolderDefinition == null)
            {
                GetRadioButtonLocationTypeGeneral().attr("checked", true);
                GetSpanLocation().text("");
                GetDropDownContentType().empty();

                //TODO: reset application property & service property dropdowns
            }
            else
            {
                GetRadioButtonLocationTypeSpecific().attr("checked", true);
                GetDropDownSiteSetting().val(mapping.BasicFolderDefinition.SiteSettingID);

                var path = mapping.BasicFolderDefinition.FolderUrl;
                GetSpanLocation().text(path);

                var siteSettingUrl = GetDropDownSiteSettingSelectedText();
                this.SelectedFolderType = mapping.BasicFolderDefinition.FolderType;

                //fill the CT dropdownlists
                SCA.DAL.SP.GetWebUrlFromUrl(siteSettingUrl, path, Function.createDelegate(this, function (webUrl) {
                    var listName = this.GetListNameFromAbsoluteUrl(webUrl, path);
                    var list = new SCA.DAL.List(listName, webUrl);
                    list.Load(function () {
                        FillDropDownList(list.contentTypeCollection, GetDropDownContentType(), function (item) { return item.id; }, function (item) { return item.title; });
                        GetDropDownContentType().val(mapping.ItemPropertyMappings[0].ContentTypeID);
                    });

                }),
                function (data) { console.error("SCA.UI.Mappings.Dialog: " + data); });

                //TODO: for application property & service property dropdowns

                GetInputServiceProperty().val("");
            }

            GetHiddenInputIndex().val(index);
            ShowHideLocationControls();
        }
        catch (ex) {
            alert("SCA.UI.Mappings.Dialog - Load(): " + ex.message);
        }
    }

    //TODO: duplication 
    this.GetListNameFromAbsoluteUrl = function (webSiteUrl, absoluteUrl) {
        var n = webSiteUrl.length;
        var charsToRemove = (webSiteUrl.charAt(n - 1) != '/') ? n + 1 : n;

        var partialUrl = absoluteUrl.substring(charsToRemove).toLowerCase();

        var tokensOfPartialUrl = partialUrl.split("/");

        var listName = (partialUrl.indexOf("lists/") == 0) ? tokensOfPartialUrl[1] : tokensOfPartialUrl[0];

        return listName;
    }


    this.OpenLocationTree = function () {
        var treeParams = {
            allowSelectWeb: false,
            allowSelectList: true,
            allowSelectFolder: false,
            exploreDepth: "List"
        }

        this.LocationSelectionDialog = new SCA.UI.LocationSelection.Dialog("Location selection", GetDropDownSiteSettingSelectedText(), treeParams, SelectLocationCallback);
        this.LocationSelectionDialog.Open();
    }

    var SelectLocationCallback = function (result) {
        if (result != null) {
            GetSpanLocation().text(result.absoluteUrl);

            this.SelectedFolderType = (result instanceof SCA.DAL.List)
                                        ? FOLDER_TYPE_LIST
                                        : (result instanceof SCA.DAL.Folder)
                                            ? FOLDER_TYPE_FOLDER
                                            : null;

            result = (result instanceof SCA.DAL.List) ? result : result.parentList;
            FillDropDownList(result.contentTypeCollection, GetDropDownContentType(), function (item) { return item.id; }, function (item) { return item.title; });
        }
    }

    var FillAllDropDownLists = function () {
        FillDropDownList(SCA.AppConfiguration.SiteSettings, GetDropDownSiteSetting(), function (item) { return item.ID; }, function (item) { return item.Url; });
    }

    //TODO: duplicated
    var FillDropDownList = function (listOfItems, dropDownList, valueDelegate, textDelegate) {
        dropDownList.html("");

        if ((listOfItems != null) && (listOfItems.length > 0))
            for (var i = 0; i < listOfItems.length; i++) {
                var item = listOfItems[i];
                jQuery("<option value='" + valueDelegate(item) + "'>" + textDelegate(item) + "</option>").appendTo(dropDownList);
            }
    }

    this.Validate = function () {

        jQuery.validity.setup({ outputMode: "modal" });

        jQuery.validity.start();
        
        //TODO: 

        var result = jQuery.validity.end();

        return result.valid;
    }

    this.Close = function () {
        GetDialog().dialog("close");
    }

    this.Save = function () {

        var isValid = this.Validate();
        if (!isValid)
            return;

        var index = GetHiddenInputIndex().val();

        var isNewItem = false;
        if (index == -1) //it's a new mapping
        {
            index = SCA.AppConfiguration.FolderSettings.push({}) - 1;
            isNewItem = true;
        }

        var isGeneralLocation = GetRadioButtonLocationTypeGeneral().is(':checked');

        var mapping = GetMapping(index);

        if (isNewItem)
        {
            mapping.ItemPropertyMappings = new Array();
            var newGuid = SP.Guid.newGuid().toString();
            mapping.ItemPropertyMappings.push({ "ID": newGuid }); 
        }
       

        mapping.ApplicationType = GetSelectedRadioButtonApplicationType().val();
        mapping.ItemPropertyMappings[0].ApplicationPropertyName = GetDropDownApplicationPropertySelectedText();

        if (isGeneralLocation)
        {
            delete mapping.BasicFolderDefinition;
            delete mapping.ItemPropertyMappings[0].ContentTypeID;
            delete mapping.ItemPropertyMappings[0].FolderDisplayName;
            
            mapping.ItemPropertyMappings[0].ServicePropertyName = GetInputServiceProperty().val();
        }
        else
        {
            mapping.ItemPropertyMappings[0].ContentTypeID = GetDropDownContentType().val();
            mapping.ItemPropertyMappings[0].FolderDisplayName = "what folder"; //TODO: what folder?
            mapping.ItemPropertyMappings[0].ServicePropertyName = GetDropDownServicePropertySelectedText();

            mapping.BasicFolderDefinition = {
                "Folders": new Array(),
                "SiteSettingID": GetDropDownSiteSetting().val(),
                "Title": "list title",
                "FolderUrl": GetSpanLocation().text(),
                "FolderType" : FOLDER_TYPE_LIST
            }
        }

        if (isNewItem) {
            this.mappingsTable.AddRow(index);
        }
        else {
            this.mappingsTable.RefreshRow(index);
        }

        this.Close();
    }

    var GetMapping = function (index) {
        return SCA.AppConfiguration.FolderSettings[index];
    }

    var GetDialog = function () {
        return jQuery("#MappingEditDialog");
    }
  
    var GetRadioButtonApplicationType = function (mapping) {
        var idRadioButtonApplicationType = "#RadioButtonMappingDialogApplicationType" + mapping.ApplicationType;
        return jQuery(idRadioButtonApplicationType);
    }

    var GetFirstRadioButtonApplicationType = function () {
        return jQuery("input[name=MappingApplicationType]:first");
    }

    var GetSelectedRadioButtonApplicationType = function () {
        return jQuery("input[name=MappingApplicationType]:checked");
    }

    var GetRadioButtonLocationTypeGeneral = function () {
        return jQuery("#RadioButtonMappingDialogLocationTypeGeneral");
    }

    var GetRadioButtonLocationTypeSpecific = function () {
        return jQuery("#RadioButtonMappingDialogLocationTypeSpecific");
    }

    var GetFirstRadioButtonLocationType = function () {
        return jQuery("input[name=MappingLocationType]:first");
    }

    var GetSelectedRadioButtonLocationType = function () {
        return jQuery("input[name=MappingLocationType]:checked");
    }

    var GetDropDownSiteSetting = function () {
        return jQuery("#DropDownMappingDialogSiteSetting");
    }

    var GetDropDownSiteSettingSelectedText = function () {
        return jQuery("#DropDownMappingDialogSiteSetting option:selected").text();
    }

    var GetSpanLocation = function () {
        return jQuery("#SpanMappingLocation");
    }

    var GetDropDownContentType = function () {
        return jQuery("#DropDownMappingDialogContentType");
    }

    var GetDropDownContentTypeSelectedText = function () {
        return jQuery("#DropDownMappingDialogContentType option:selected").text();
    }

    var GetDropDownApplicationProperty= function () {
        return jQuery("#DropDownMappingDialogApplicationProperty");
    }

    var GetDropDownApplicationPropertySelectedText = function () {
        return jQuery("#DropDownMappingDialogApplicationProperty option:selected").text();
    }

    var GetDropDownServiceProperty = function () {
        return jQuery("#DropDownMappingDialogServiceProperty");
    }

    var GetDropDownServicePropertySelectedText = function () {
        return jQuery("#DropDownMappingDialogServiceProperty option:selected").text();
    }

    var GetInputServiceProperty = function()
    {
        return jQuery("#InputMappingDialogServiceProperty");
    }

    var GetHiddenInputIndex = function () {
        return jQuery("#HiddenFieldMappingDialogCurrentIndex");
    }

    this.Setup();
}